//
//  CFBTTabBarVC.h
//  半糖框架
//
//  Created by afro on 15/12/9.
//  Copyright © 2015年 afro. All rights reserved.
//

#import "BTTabBar.h"
#import "UIView+Extension.h"

@interface BTTabBar()

// 中间的添加按钮
@property (nonatomic, weak)UIButton * plusBtn;

@end

@implementation BTTabBar
- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        // 自定义该类（UIView子类）的初始化操作，添加一个按钮到tabbar中
        UIButton *plusBtn = [[UIButton alloc] init];
        
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tab_publish_add"]
                           forState:UIControlStateNormal];
        
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tab_publish_add_pressed"]
                           forState:UIControlStateHighlighted];
        
        plusBtn.size = plusBtn.currentBackgroundImage.size;
        
        [plusBtn addTarget:self action:@selector(plusClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:plusBtn];
        
        self.plusBtn = plusBtn;
    }
    
    return self;
}

// 加号按钮点击
- (void)plusClick
{
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickPlusButton:)]) {
        [self.delegate tabBarDidClickPlusButton:self];
    }
    //NSLog(@"WTF!");
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 更改tabBarItem中图标和文字的相对位置,可以使图标居中,文字隐藏
    CGFloat iconOffset = 5.0;
    CGFloat labelOffset = 12.0;
    for (UITabBarItem *item in self.items) {
        item.imageInsets = UIEdgeInsetsMake(iconOffset, 0, -iconOffset, 0);
        item.titlePositionAdjustment = UIOffsetMake(0, labelOffset);
    }
    
    // 1.设置加号按钮的位置
    self.plusBtn.centerX = self.width * 0.5;
    self.plusBtn.centerY = self.height * 0.5;
    
    // 2.设置其他tabbarButton的位置和尺寸
    CGFloat tabbarButtonW = self.width / 5;
    CGFloat tabbarButtonIndex = 0;
    for (UIView *child in self.subviews) {
        Class class = NSClassFromString(@"UITabBarButton");
        
        if ([child isKindOfClass:class]) {
            
            // 设置宽度
            child.width = tabbarButtonW;
            
            // 设置x
            child.x = tabbarButtonIndex * tabbarButtonW;
            
            // 增加索引
            tabbarButtonIndex++;
            
            if (tabbarButtonIndex == 2) {
                
                tabbarButtonIndex++;
                
            }
        }
    }
}

@end
